﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Kingzad.MicroService.BusinessCore.Providers
{
    public interface IMongoProvider
    {
        Task InsertAsync(BsonDocument obj);
        Task DeleteAsync(BsonDocument obj);
        Task<IEnumerable<BsonDocument>> GetList(FilterDefinition<BsonDocument> filter);
    }

    public class MongoProvider : IMongoProvider
    {
        private readonly IMongoConnectionFactory _mongoConnectionFactory;
        IMongoDatabase _db;
        IMongoCollection<BsonDocument> collection;

        public MongoProvider(IMongoConnectionFactory mongoConnectionFactory, string tableName)
        {
            _mongoConnectionFactory = mongoConnectionFactory;
            collection = _mongoConnectionFactory.GetConnection().GetCollection<BsonDocument>(tableName);
        }


        public async Task InsertAsync(BsonDocument obj)
        {
            await collection.InsertOneAsync(obj);
        }

        public async Task DeleteAsync(BsonDocument obj)
        {
            await collection.DeleteOneAsync(obj);
        }

        public async Task<IEnumerable<BsonDocument>> GetList (FilterDefinition<BsonDocument> filter)
        {
            var result = await collection.FindAsync(filter);
            return result.ToEnumerable();
        }
    }
}
